<?php
namespace control;
/*
*费用单类
*/

class otherOutReceiptClass extends adIndexClass
{
    private const page = 'otherOutReceipt';
    private const table = 'other_receipt';
    private const tableMx = 'other_receipt_detail';
    private const tableSource = 'receipt_source';
    private const title = '费用单';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => L('finance.table.dan_ju_bian_hao'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'target'  => [
                        'name'  => L('finance.table.ye_wu_lei_xing'),
                        'width' => 200,
                    ],
                    'targetName'         => [
                        'name'  => L('finance.table.wldw'),
                        'width' => 300,
                    ],
                    'money'          => [
                        'name'  => L('finance.table.jin_e') . "(" . static::$unit . ")",
                        'width' => 200,
                    ],
                    'manager'          => [
                        'name'  => L('finance.table.fu_kuan_ren'),
                        'width' => 200,
                    ],
                    'recordDate'          => [
                        'name'  => L('finance.table.dan_ju_ri_qi'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => L('finance.table.zhuang_tai'),
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('finance.table.dan_ju_bian_hao') => text(array("name" => "orderNo")),
                    L('finance.table.wldw')   => text(array("name" => "targetName")),
                    L('finance.table.dan_ju_ri_qi') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    L('finance.table.zhuang_tai') => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('finance.table.otherOutReceiptInfo') . "','" . $url . "&fun=edit')\" class='spanButton'>" . L('finance.table.add') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('finance.table.shan_chu') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*供应商列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            "targetName" => $this->post('targetName'),
            'coid' => self::$coid
        );
        $and = " and classify = 1";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => L('finance.table.bian_ji'), "click" => "newIframe('" . L('finance.table.otherOutReceiptInfo') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => L('finance.table.otherOutReceiptInfo'), "click" => "newIframe('" . L('finance.table.otherOutReceiptInfo') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'money':
                        //付款金额
                        $money = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]'", 'sum' => "money"));
                        $row[] = $money;
                        break;
                    case 'manager':
                        $row[] = self::findStaff($array['manager']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx,
            'single' => " orderId in (select id from ".self::table." where 1=1 {$where}) ",
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'        => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            "name" => '保存为草稿',
            "type" => '点击事件',
            "title" => '保存为草稿',
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        $inRecObj = new otherInReceiptClass();
        $tr[] = ['', L('finance.table.szxm'),  L('finance.table.payMoney') . '(' . static::$unit . ')', L('finance.table.bei_zhu')];
        $result = find(array(
            'field' => "id as mxId,project,money as income,text as mxText",
            'table' => self::tableMx." where orderId = '$info[id]' order by list"
        ));
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $tr[] = $this->listRow($array);
            }
        }else{
            $tr[] = $this->listRow(['mxId'=>self::getId(), 'list'=>1]);
        }

        $checkMoneyTotal = 0;
        $sourceTr[] = [L('finance.table.cao_zuo'), L('finance.table.ydbh'), L('finance.table.ye_wu_lei_xing'), L('finance.table.dan_ju_ri_qi'), L('finance.table.jsfs'), L('finance.table.jsqx'), L('finance.table.cpbm'), L('finance.table.cpmc'), L('finance.table.gui_ge_xing_hao'), L('finance.table.dan_wei'), L('finance.table.shu_liang'), L('finance.table.dan_jia'), L('finance.table.jin_e'), L('finance.table.ftfy')];
        $result = find(array('table' => self::tableSource, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($result['array'] as $k=>$array) {

            if ($array['sourceTable'] == 'purchase_get_order_detail') {
                $mx = query('purchase_get_order_detail', "id = '$array[sourceId]'");
                $order = query('purchase_get_order', "id = '$mx[orderId]'");
                $type = L('finance.table.cgsh');
            } else {
                $mx = query('sale_send_order_detail', "id = '$array[sourceId]'");
                $order = query('sale_send_order', "id = '$mx[orderId]'");
                $type = L('finance.table.xsfh');
            }
            $material = query('material', "id = '$mx[materialId]'");
            $sourceTr[] = array(
                componentClass::tablePperation($k+1,"delTableRow(this)").
                hidden(array('name' => 'detailId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'sourceId[]', 'value' => $array['sourceId'])),
                $order['orderNo'],
                $type,
                $order['recordDate'],
                $order['settlementType'],
                $order['settlementDay'],
                $material['code'],
                $material['name'],
                $material['model'],
                $material['unit'],
                self::lostZero($mx['num'],'num'),
                self::lostZero($mx['price'],'price'),
                "<span class='sourceMoney'>".self::lostZero($mx['money'])."</span>",
                text(array('name' => 'money[]', 'value' => $array['money'], 'blur' => "countMoney", 'type' => 'number'))
            );
            $checkMoneyTotal += $array['money'];
        }
        $total_tr = [
            13 => "<span id='checkMoneyTotal'>".$checkMoneyTotal."</span>",
        ];
        $list = $this->listTable(array('tr' => $sourceTr, 'end' => true, 'total' => $total_tr));
        $chooseOrder = L('finance.table.chooseOrder');
        $disMoneyTotal = L('finance.table.disMoneyTotal');
        $but = <<<efo
                <span class="smallButton" onclick="chooseOrder()">$chooseOrder</span>
efo;
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    L('finance.table.ye_wu_lei_xing') . "：" => radio(array('name' => 'type', 'value' => ['付款结算' => L('finance.table.paySettle'),'其他应付' => L('finance.table.otherPay')], 'checked' => $info['type'] ?: '付款结算')),
                    L('finance.table.wldw') . "：" => text(array('name' => 'targetName', 'id' => 'targetName', 'value' => $info['targetName'])) . hidden(array('name' => 'targetId', 'value' => $info['targetId'])) . hidden(array('name' => 'target', 'value' => $info['target'])),
                    must . L('finance.table.dan_ju_ri_qi') . "：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    L('finance.table.ftfs') . "：" => radio(array('name' => 'shareType', 'value' => ['按数量' => L('finance.table.an_shu_liang'), '按金额' => L('finance.table.an_jin_e')], 'checked' => $info['shareType'])),
                ],
                [
                    must ."结算账户："=>componentClass::subjectComponent(['name' => 'acid','value'=>$info['acid'], 'inputName' => 'costSubjectName', 'isShowParent' => false]),
                    L('finance.table.fu_kuan_ren') . "：" => selectMultiple(["name" => "manager", "value" => $info['manager'] ?: self::$stid, 'where' => "state !='离职'", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => L('finance.table.qing_xuan_ze')]),
                ],
                [
                    L('finance.table.text') . "：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'title' => L('finance.table.fymx'),
            'html' => $this->listTable(array('tr' => $tr, 'end' => true)),
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => L('finance.table.disMx'),
            'button' => $but,
            'html' => $list,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= <<<efo
<script>
$("#targetName").bigAutocomplete({
    width:200,
    url:root + 'control/adIndex.html?cla=otherInReceipt&fun=getCompany',
    callback:function(data,e){
       e.siblings("input[name='targetId']").val(data.id)
       $("[name='target']").val(data.target)
}}) 
function addRow(e){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{},function (res){
            $(e).closest('tr').after(res.data);
            resetNumber($(e).closest('tbody'))
         },'json');
}
function chooseOrder(){
    let targetId = $("[name='targetId']").val();
    if (!targetId){
        msg('请先选择往来单位','error');
        return false;
    }
    layer('{$this->get('cla')}','addOrder',$('form[name=otherOutReceiptEditForm]').serialize())
}
function addOrder(){
     $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addOrderEdit',$("form[name='orderForm']").serialize(),function (res){
            $('#otherOutReceiptAddOrder').hide()
            $("#materialTable tbody").append(res.html);
            resetNumber($("#materialTable"))
            countMoney()
         },'json');
}
function countMoney(){
    let money = 0;
    $("#materialTable [name='money[]']").each(function() {
        money+=Number($(this).val());
    })
    $("#checkMoneyTotal").html(money.toFixed(2))
}
//分摊费用
function allocatedExpense(e){
    let money = 0,income = 0;
    $("[name='income[]']").each(function() {
        income+=Number($(this).val());
    })
    $("#materialTable .sourceMoney").each(function() {
        money+=Number($(this).text());
    })
    $("#materialTable [name='money[]']").each(function() {
        let nowSourceMoney = $(this).closest('tr').find('.sourceMoney').text()
        let ratio = Number(nowSourceMoney)/Number(money)
        $(this).val((income*ratio).toFixed(2))
    })
    countMoney()
}
</script>

efo;
        //返回
        return $this->tab($data);
    }

    /**
     * 关联源单
     * @return bool|string
     */
    public function addOrder(): bool|string
    {
        $html =
            text(array("name" => "orderNo", "title" => L('finance.table.dan_ju_bian_hao'))) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('finance.table.dan_ju_ri_qi') . "-" . L('finance.table.dan_ju_ri_qi'))) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            hidden(array('name' => 'target', 'value' => $this->post('target'))) .
            hidden(array('name' => 'targetId', 'value' => $this->post('targetId'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addOrder()\" type='button' class='searchSub' value='" . L('finance.table.ti_jiao') . "'>";
        $html = $this->search($html);
        return $this->layer(array("title" => L('finance.table.tian_jia'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 关联源单
     * @return bool|string
     */
    public function addOrderSearch(): bool|string
    {
        $targetId = $this->post('targetId');
        $target = $this->post('target');
        $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        $where = " a.coid='" . self::$coid . "' and b.id not in ('" . implode("','", $sourceId) . "')";
        $and = '';
        $like = [
            'orderNo' => $this->post('orderNo'),
        ];
        $equal = [
            'state' => '已确认',
        ];
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        if ($target == '客户') {
            $where .= " and khid = '$targetId'";
            $page = $this->page([
                'field' => "b.*,a.recordDate,a.orderNo,a.settlementType,a.settlementDay",
                "table" => "sale_send_order as a join sale_send_order_detail as b",
                "where" => $where,
                'pageNum' => 50,
                "order" => "`recordDate` desc,`orderNo` asc",
            ]);
        } else {
            $where .= " and supplierId = '$targetId'";
            $page = $this->page([
                'field' => "b.*,a.recordDate,a.orderNo,a.settlementType,a.settlementDay",
                "table" => "purchase_get_order as a join purchase_get_order_detail as b",
                "where" => $where,
                'pageNum' => 50,
                "order" => "`recordDate` desc,`orderNo` asc",
            ]);
        }

        //获取表头
        $checkAll = $this->checkAll("orderForm", "orderId");
        $tr[] = [$checkAll, L('finance.table.dan_ju_bian_hao'), L('finance.table.dan_ju_ri_qi'), L('finance.table.jsfs'), L('finance.table.jsqx'), L('finance.table.cpbm'), L('finance.table.cpmc'), L('finance.table.gui_ge_xing_hao'), L('finance.table.dan_wei'), L('finance.table.shu_liang'), L('finance.table.dan_jia'), L('finance.table.jin_e')];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "orderId", "value" => $array['id']),
            );
            $material = query('material', "id = '$array[materialId]'");
            $tr[] = array(
                $this->dominate($dominate),
                $array['orderNo'],
                $array['recordDate'],
                $array['settlementType'],
                $array['settlementDay'],
                $material['code'],
                $material['name'],
                $material['model'],
                $material['unit'],
                self::lostZero($array['num'],'num'),
                self::lostZero($array['price'],'price'),
                self::lostZero($array['money']),
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='orderForm'>" .
                hidden(array('name' => 'target', 'value' => $target)) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 关联源单
     */
    public function addOrderEdit(): bool|string
    {
        $target = $this->post('target');
        $mxIdArr = $this->post('orderId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('finance.table.nhmzbjzx');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('finance.table.qxzyd');
        } elseif (empty($target)) {
            $json['warn'] = L('finance.table.wxzwldw');
        } else {
            $tr = [];
            foreach ($mxIdArr as $id) {
                if ($target == '客户') {
                    $mx = query('sale_send_order_detail', "id = '$id'");
                    $info = query('sale_send_order', "id = '$mx[orderId]'");
                    $type = L('finance.table.xsfh');
                } else {
                    $mx = query('purchase_get_order_detail', "id = '$id'");
                    $info = query('purchase_get_order', "id = '$mx[orderId]'");
                    $type = L('finance.table.cgsh');
                }

                $material = query('material', "id = '$mx[materialId]'");
                $tr[] = array(
                    componentClass::tablePperation('',"delTableRow(this)").
                    hidden(array('name' => 'detailId[]', 'value' => suiji())) .
                    hidden(array('name' => 'sourceId[]', 'value' => $id)),
                    $info['orderNo'],
                    $type,
                    $info['recordDate'],
                    $info['settlementType'],
                    $info['settlementDay'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
                    self::lostZero($mx['num'],'num'),
                    self::lostZero($mx['price'],'price'),
                    "<span class='sourceMoney'>".self::lostZero($mx['money'])."</span>",
                    text(array('name' => 'money[]', 'blur' => "countMoney", 'type' => 'number'))
                );
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        }
        return json_encode($json, 320);
    }

    /**
     * Desc : 费用明细
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function listRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['mxId'])&&$data['mxId']?$data['mxId']:self::getId();
        $field = ['project', 'income', 'mxText'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        $cloneArg = json_encode([
            'cla' => self::page,
            'fun' => 'listRow',
            'copy' => $field,
        ],320);
        $delArg = json_encode([
            'empty' => $field,
        ],320);
        $inRecObj = new otherInReceiptClass();
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg)","cloneRows(this,$cloneArg)", "addRow(this)"),
            hidden(array('name' => 'mxId[]', 'value' => $mxId)) .
            select(array('name' => 'project[]', 'title' => L('finance.table.qing_xuan_ze'), 'option' => $inRecObj->inOutType('支'), 'value' => $array['project'])),
            text(array('name' => 'income[]', 'keyup' => 'allocatedExpense', 'value' => $array['income'])),
            text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => $array['mxText'])),
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $res = json_decode($this->listRow(),true);
        $json['data'] = $res['html'];
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //付款
        $mxIdArr = $this->post('mxId') ?: [];
        $incomeArr = $this->post('income');
        $projectArr = $this->post('project');
        $mxTextArr = $this->post('mxText');
        //源单
        $detailIdIdArr = $this->post('detailId') ?: [];
        $sourceIdArr = $this->post('sourceId');
        $checkMoneyArr = $this->post('money') ?: [];
        $field = [
            'type' => $this->post('type'),
            'shareType' => $this->post('shareType'),
            'target' => $this->post('target'),
            'targetId' => $this->post('targetId'),
            'targetName' => $this->post('targetName'),
            'text' => $this->post('text'),
            'recordDate' => $this->post('recordDate'),
            'manager' => $this->post('manager'),
            'acid'=>$this->post('acid'),
        ];
        $where = " id = '$id' ";
        $info = query(self::table, $where);

        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('finance.table.fee_edit_permission');
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = L('finance.table.cfydyqrbnxg');
        } else {
            $this->startTrans();
            $isPass = true;//事务通过标志
            if (!$info['id']) {
                $userNo = $orderNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'QTZC' . date('Ymd',strtotime($field['recordDate'])),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " and coid = '" . self::$coid . "'",
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'state' => '草稿',
                    'classify' => 1,
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
                $orderNo = $info['orderNo'];
            }

            //结算信息
            foreach ($mxIdArr as $k => $nid) {
                $mx = query(self::tableMx, "id = '$nid'");
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::tableMx,
                        "field" => [
                            'money' => $incomeArr[$k],
                            'project' => $projectArr[$k],
                            'text' => $mxTextArr[$k],
                        ],
                        "where" => " id = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::tableMx,
                        "field" => [
                            'id' => $nid,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'money' => $incomeArr[$k],
                            'project' => $projectArr[$k],
                            'text' => $mxTextArr[$k],
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $isPass = false;
                    $json['warn'] = $warn;
                    break;
                }
                if ($field['type'] == '付款结算' && $field['acid']) {

                    //生成记账表
                    $bookkeeping = query('bookkeeping', "sourceId = '$nid'");
                    $account = query('account', "subjectId = '$field[acid]'");
                    if (!$account['id']) {
                        $json['warn'] = '未找到结算账户';
                    }
                    if (empty($bookkeeping['id'])) {
                        $page = $account['type'] == '现金' ? 'cashBook' : 'bankBook';
                        $fieldBookkeeping = [
                            'id' => suiji(),
                            'type' => $account['type'] == '现金' ? '现金' : '银行账户',
                            'coid' => self::$coid,
                            'stid' => self::$stid,
                            'accountId' => $account['id'],
                            'classify' => $projectArr[$k],
                            'recordDate' => $field['recordDate'],
                            'company' => $field['targetName'],
                            'summary' => "费用单【{$orderNo}】",
                            'expenses' => $incomeArr[$k],
                            'text' => $mxTextArr[$k],
                            'sourceTable' => self::tableMx,
                            'sourceId' => $nid,
                        ];
                        $userNo = codeTemplateClass::generateCode($page, [
                            'prefix' => date('Ymd',strtotime($field['recordDate'])),
                            'table' => 'bookkeeping',
                            'field' => 'orderNo',
                            'where' => '',
                        ], $fieldBookkeeping);
                        $fieldBookkeeping['orderNo'] = $userNo;
                        $warn = static::insert([
                            "table" => "bookkeeping",
                            "field" => $fieldBookkeeping,
                        ]);
                    }
                    else {
                        $warn = static::update([
                            "table" => "bookkeeping",
                            "field" => [
                                'accountId' => $account['id'],
                                'classify' => $projectArr[$k],
                                'recordDate' => $field['recordDate'],
                                'company' => $field['targetName'],
                                'summary' => "费用单【{$orderNo}】",
                                'expenses' => $incomeArr[$k],
                                'text' => $mxTextArr[$k],
                            ],
                            'where' => "id = '$bookkeeping[id]'"
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass = false;
                        $json['warn'] = L('finance.table.scjzbsb');
                        break;
                    }
                }

            }

            foreach ($detailIdIdArr as $k => $mxId) {
                //销售发货单
                $targetInfo = query('sale_send_order_detail', "id = '$sourceIdArr[$k]'");
                $table = 'sale_send_order_detail';
                if (empty($targetInfo['id'])) {
                    //采购收货单
                    $targetInfo = query('purchase_get_order_detail', "id = '$sourceIdArr[$k]'");
                    $table = $targetInfo['id'] ? 'purchase_get_order_detail' : '';
                }
                $mx = query(self::tableSource, "id = '$mxId'");
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::tableSource,
                        "field" => [
                            'sourceTable' => $table,
                            'sourceId' => $sourceIdArr[$k],
                            'money' => $checkMoneyArr[$k],
                        ],
                        "where" => " id = '$mxId'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::tableSource,
                        "field" => [
                            'id' => $mxId,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'sourceTable' => $table,
                            'sourceId' => $sourceIdArr[$k],
                            'money' => $checkMoneyArr[$k],
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $isPass = false;
                    $json['warn'] = $warn;
                    break;
                }
            }


            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(array('table' => 'bookkeeping', 'where' => " sourceId in (select id from " . self::tableMx . " where id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id') and coid = '" . self::$coid . "'"));
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                delete(array('table' => self::tableSource, 'where' => " id not in ('" . implode("','", $detailIdIdArr) . "') and orderId = '$id'"));
                if ($json['warn'] == '新增成功') {
                    self::insertOperateLog($id,self::title,"新建");
                }
                //添加日志
                $text = str_replace(['{{staffName}}', '{{orderNo}}', '{{id}}'], [$this->control['name'], $orderNo, $id], L('finance.table.fee_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('finance.table.wzdcfyd');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => '复核',
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }

            if ($info['state'] == '草稿') {
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => L('finance.table.ti_jiao'),
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name" => L('finance.table.bian_ji'),
                        "type" => "顶部页卡",
                        "title" => L('finance.table.bian_ji'),
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    ];
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => L('finance.table.shan_chu'),
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }
            if ($this->power(self::page, "cancel") && $info['state'] != '草稿') {
                $button[] = [
                    "name" => "撤销",
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id'],1);

            $tr[] = [L('finance.table.szxm'),  L('finance.table.payMoney') . '(' . static::$unit . ')', L('finance.table.bei_zhu')];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $tr[] = [
                    $array['project'],
                    $array['money'],
                    $array['text'],
                ];
            }
            $income = find(array('table' => self::tableMx, 'sum' => "money", 'where' => "orderId = '$info[id]'"));
            $total_tr = [
                    1=>$income
            ];

            $sourceTr[] = [L('finance.table.ydbh'), L('finance.table.ye_wu_lei_xing'), L('finance.table.dan_ju_ri_qi'), L('finance.table.jsfs'), L('finance.table.jsqx'), L('finance.table.cpbm'), L('finance.table.cpmc'), L('finance.table.gui_ge_xing_hao'), L('finance.table.dan_wei'), L('finance.table.shu_liang'), L('finance.table.dan_jia'), L('finance.table.jin_e'), L('finance.table.ftfy')];
            $result = find(array('table' => self::tableSource, 'where' => "orderId = '$info[id]' order by list"));
            $num = $money = 0;
            foreach ($result['array'] as $array) {
                if ($array['sourceTable'] == 'purchase_get_order_detail') {
                    $mx = query('purchase_get_order_detail', "id = '$array[sourceId]'");
                    $order = query('purchase_get_order', "id = '$mx[orderId]'");
                    $type = L('finance.table.cgsh');
                } else {
                    $mx = query('sale_send_order_detail', "id = '$array[sourceId]'");
                    $order = query('sale_send_order', "id = '$mx[orderId]'");
                    $type = L('finance.table.xsfh');
                }
                $material = query('material', "id = '$mx[materialId]'");
                $sourceTr[] = [
                    $order['orderNo'],
                    $type,
                    $order['recordDate'],
                    $order['settlementType'],
                    $order['settlementDay'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
                    self::lostZero($mx['num'],'num'),
                    self::lostZero($mx['price'],'price'),
                    self::lostZero($mx['money']),
                    self::lostZero($array['money'])
                ];
                $num += $mx['num'];
                $money += $mx['money'];
            }
            //本次核销金额
            $offMoney = find(array('table' => self::tableSource, 'where' => "orderId = '$info[id]'", 'sum' => "money"));
            $total_source_tr = [
                    9=>self::formattingFigure($num,'numPrecision'),
                    11=>self::formattingFigure($money),
                    12=>self::formattingFigure($offMoney)
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                array(
                    array(
                        L('finance.table.ye_wu_lei_xing') => $info['type'],
                        L('finance.table.wldw') => $info['targetName'],
                        L('finance.table.dan_ju_ri_qi') => $info['recordDate'],
                        '结算账户' =>  subjectClass::getShortName($info['acid'],'code'). subjectClass::getName($info['acid']),
                    ),
                    array(
                        L('finance.table.ftfs') => $info['shareType'],
                        L('finance.table.fu_kuan_ren') => self::findStaff($info['manager']),
                        L('finance.table.dan_ju_bian_hao') => $info['orderNo'],
                        L('finance.table.zhi_dan_ren') => self::findStaff($info['stid']),
                    ),
                    array(
                        L('finance.table.zhuang_tai') => $info['state']
                    ),
                    array(
                        L('finance.table.bei_zhu') => pre($info['text']),
                    ),

                )
            ));
            $data['html'] .= $this->detailList([
                'title' => L('finance.table.fymx'),
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => L('finance.table.yuan_dan_ju'),
                'html' => $this->listTable(array('tr' => $sourceTr, 'showEmpty' => true, 'total' => $total_source_tr, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 确认
     */
    public function confirmEdit(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = L('finance.table.nhmzqrzx');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('finance.table.wzdcfyd');
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = L('finance.table.cfydbsdqrztbnqr');
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if ($info['type'] == '收款结算') {
                $all = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
                foreach ($all['array'] as $array) {
                    $account = query('account',"subjectId = '$info[acid]'");
                    $bool = accountClass::record_ac($account['id'], '支出', $array['money'], "费用单【{$info['orderNo']}】支出", targetName: $info['targetName'], targetDate: $info['recordDate'], orderNo: $info['orderNo'], hiddenText: "费用单【{$info['orderNo']}】支出，明细ID：{$array['id']}");
                    if ($bool !== true) {
                        $json['warn'] = $bool;
                        break;
                    }
                }
            }
            if ($info['type'] == '其他应付') {
                $remindMoney = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]'", 'sum' => "money"]);
                if ($info['target'] =='客户'){
                    $bool = supplierClass::record_cl($info['targetId'], '+', -$remindMoney, $info['recordDate'], self::table, $info['id'], "费用单【{$info['orderNo']}】收款", orderNo: $info['orderNo'], hiddenText: "费用单类型为其他应付", classify: $info['type']);
                }else{
                    $bool = supplierClass::record_cl($info['targetId'], '-', $remindMoney, $info['recordDate'], self::table, $info['id'], "费用单【{$info['orderNo']}】收款",'供应商', orderNo: $info['orderNo'], hiddenText: "费用单类型为其他应付", classify: $info['type']);
                }
                if ($bool !== true) {
                    $json['warn'] = $bool;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])) {
                    self::insertOperateLog($info['id'],self::title,"提交、复核");
                }else{
                    self::insertOperateLog($info['id'],self::title,"复核");
                }
                $this->commitTrans();
                //添加日志
                $text = str_replace(['{{staffName}}', '{{orderNo}}', '{{id}}'], [$this->control['name'], $info['orderNo'], $id], L('finance.table.fee_confirm_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * Desc : 提交前数据验证
     * User : you name
     * Date : 2023-11-17 16:04
     * @param $info
     * @return string|bool
     */
    public function dataValidation($info): string|bool
    {
        $annotation = [
            'type' => L('finance.table.ye_wu_lei_xing'),
            'recordDate' => L('finance.table.dan_ju_ri_qi'),
            'acid'=>'结算账户'
        ];
        $rules = [
            'type' => 'required',
            'recordDate' => 'required|date',
            'acid' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($info, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0];  // 多个规则提示最前面一条
        }
        if ($info['type'] == '其他应付' && empty($info['targetId'])) {
            return '请选择往来单位';
        }
        $result = find(array('table' => self::tableMx, 'field' => 'id,money,project', 'where' => "orderId = '$info[id]' order by list"));
        if(count($result['array']) == 0){
            return "请完善费用明细";
        }
        if(static::is_null_array(array_column($result['array'],'project'))){
            return "费用明细中【收支项目】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'money'),false)){
            return "费用明细中【付款金额】不能为空，且必须大于0";
        }
        $totalInCom = self::formattingFigure(array_column($result['array'],'money'));
        $checkMoneyArr = find(array('table' => self::tableSource, 'where' => " orderId = '$info[id]' ", 'sum' => "money"));
        //总分摊金额
        $totalCheckMoney = self::formattingFigure($checkMoneyArr);
        if ($totalCheckMoney > $totalInCom) {
            return L('finance.table.bcftjecglfkje');
        }
        return true;
    }
    /**
     * 提交
     */
    public function commitEdit(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        //提交前数据验证
        $json['warn'] = $this->dataValidation($info);
        if($json['warn'] !== true){
            goto resp;
        }
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('finance.table.nhmzbjzx');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('finance.table.wzdcfyd');
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = L('finance.table.cfydbscgztbntj');
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])){
                    $resultJson = $this->confirmEdit();
                    $json = json_decode($resultJson,true);
                    if ($json['warn'] != 2){
                        $this->rollback();
                        goto resp;
                    }
                }else {
                    self::insertOperateLog($info['id'],self::title,"提交");
                }
                $this->commitTrans();
                //添加日志
                $text = str_replace(['{{staffName}}', '{{orderNo}}', '{{id}}'], [$this->control['name'], $info['orderNo'], $id], L('finance.table.fee_commit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤销
     */
    public function cancelEdit()
    {
        $id    = $this->post('id');
        $info  = query(self::table, " id = '$id'");
        $field = [
            'state'       => '草稿',
            'checkId'     => '',
            'confirmTime' => '',
        ];
        $warn='';
        if ($info['type'] =='其他应付'){
            $record = query('record', "typeId = '$info[targetId]' and coid = '" . self::$coid . "' and sourceId = '$info[id]'");
            if ($record['id'] && static::total(array('table' => 'record', 'where' => "typeId = '$info[targetId]' and coid = '" . self::$coid . "' and id > '$record[id]'")) > 0) {
                $warn     = "{$info['target']}【{$info['targetName']}】已生成了后续应付应收记录，不能撤销";
            }
        }
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤销权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此单据';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此单据不是已确认状态，无需撤销';
        } elseif ($warn) {
            $json['warn'] = $warn;
        } elseif ($info['voucherId']) {
            $json['warn'] = '此单据已生成凭证，不能撤销';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //删除应收应付记录
                delete(array('table' => 'record', 'where' => "typeId = '$info[targetId]' and coid = '" . self::$coid . "' and sourceId = '$info[id]'"));
                self::insertOperateLog($id,self::title,"撤销");
                //添加日志
                $text = $this->control['name'] . "撤销了" . self::title . "，单据编号【{$info['orderNo']}】id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = L('finance.table.que_ren');
                $title = L('finance.table.sfyqrcfydqrhjbkxg');
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = L('finance.table.bian_ji');
                $title = L('finance.table.sfqrtjcfyd');
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act      = 'cancel';
                $msg      = '撤销';
                $title    = '是否确认撤销此单据？';
                $function = 'cancelEdit';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            default:
                $act = 'del';
                $msg = L('finance.table.fee_del');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('finance.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('finance.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = L('finance.table.fee_del_failed');
                } else {
                    //最后删除基本参数
                    delete(array("table" => 'bookkeeping', "where" => " sourceId in (select id from " . self::tableMx . " where orderId = '$id')"));
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => self::tableSource, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = L('finance.table.sccg');
                    $x++;
                }
                $text .= str_replace(['{{orderNo}}', '{{id}}'], [$info['orderNo'], $info['id']], L('finance.table.fee_del_text')) . $warn . "。<br>";

            }
            //添加日志

            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('finance.table.fee_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('finance.table.fee_del_msg'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}

